//
//  LZFileFinder.m
//  LZSpamCode
//
//  Created by ZengLiZhi on 2024/6/26.
//

#import "LZFileManager.h"

@implementation LZFileManager

#pragma mark - 打开文件
+ (NSMutableString *)stringWithContentsOfFile:(NSString *)filePath{
    NSError *error = nil;
    NSMutableString *fileContent = [NSMutableString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        printf("打开文件 %s 失败：%s\n", filePath.UTF8String, error.localizedDescription.UTF8String);
        abort();
    }
    return fileContent;
}

//写入文件
+ (void)writeContent:(NSString *)content toFile:(NSString *)filePath{
    NSError *error = nil;
    [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:&error];
    if (error) {
        printf("保存文件 %s 失败：%s\n", filePath.UTF8String, error.localizedDescription.UTF8String);
        abort();
    }
}
#pragma mark - 查找文件、文件夹
+ (NSString *)findFilePath:(NSString *)inDirectory targetFileName:(NSString *)targetFileName{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray<NSString *> *files = [fm contentsOfDirectoryAtPath:inDirectory error:nil];
    BOOL isDirectory;
    NSString *findPath = nil;
    for (NSString *fileName in files) {
        NSString *filePath = [inDirectory stringByAppendingPathComponent:fileName];
        if ([fm fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {
            findPath = [self findFilePath:filePath targetFileName:targetFileName];
            if (findPath.length) {
                break;
            }
        }
        if ([fileName isEqualToString:targetFileName]) {
            return filePath;
        }
    }
    return findPath;
}

//获取文件夹path
+ (NSString *)findDirectoryPath:(NSString *)inDirectory targetName:(NSString *)targetName{
    NSFileManager *fm = [NSFileManager defaultManager];
    NSArray<NSString *> *files = [fm contentsOfDirectoryAtPath:inDirectory error:nil];
    BOOL isDirectory;
    NSString *findPath = nil;
    for (NSString *fileName in files) {
        NSString *filePath = [inDirectory stringByAppendingPathComponent:fileName];
        if ([fm fileExistsAtPath:filePath isDirectory:&isDirectory] && isDirectory) {
            //找到文件夹
            if ([fileName isEqualToString:targetName]) {
                return filePath;
            }
            
            //没找到，继续遍历
            findPath = [self findDirectoryPath:filePath targetName:targetName];
            if (findPath.length) {
                break;
            }
            
        }
    }
    return findPath;
}

#pragma mark - 通过moveItem改变文件名
+(void)renameFile:(NSString *)oldPath newPath:(NSString *)newPath {
    NSError *error;
    [[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:&error];
    if (error) {
        printf("修改文件名称失败。\n  oldPath=%s\n  newPath=%s\n  ERROR:%s\n", oldPath.UTF8String, newPath.UTF8String, error.localizedDescription.UTF8String);
        abort();
    }
}

#pragma mark - 正则匹配修改
+ (BOOL)regularReplacement:(NSMutableString *)originalString regularExpression:(NSString *)regularExpression newString:(NSString *)newString{
    return [self regularExpressionReplacement:originalString regularExpression:regularExpression newString:newString options:NSRegularExpressionUseUnixLineSeparators|NSRegularExpressionAnchorsMatchLines];
}
+ (BOOL)regularExpressionReplacement:(NSMutableString *)originalString regularExpression:(NSString *)regularExpression newString:(NSString *)newString options:(NSRegularExpressionOptions)options{
    __block BOOL isChanged = NO;
    BOOL isGroupNo1 = [newString isEqualToString:@"\\1"];
   
    //文件名带+的，需要转义，加 '\'
    if ([regularExpression containsString:@"+"]) {
        regularExpression = [regularExpression stringByReplacingOccurrencesOfString:@"+" withString:@"\\+"];
    }
    
    NSError *error = NULL;
    NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:regularExpression options:options error:&error];
    if (error) {
        // 处理错误
        NSLog(@"expression-error:%@",error);
    }
    NSArray<NSTextCheckingResult *> *matches = [expression matchesInString:originalString options:NSMatchingReportProgress range:NSMakeRange(0, originalString.length)];
    
    [matches enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(NSTextCheckingResult * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (!isChanged) {
            isChanged = YES;
        }
        
        if (isGroupNo1) {
            NSString *withString = [originalString substringWithRange:[obj rangeAtIndex:1]];
            [originalString replaceCharactersInRange:obj.range withString:withString];
        } else {
            [originalString replaceCharactersInRange:obj.range withString:newString];
        }
    }];
    return isChanged;
}
@end
